package com.relsell.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.relsell.pointofsales.R;
import com.relsell.utility.AppVars;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Add Products class adds products and their details etc to the local DB <br/>
 * and then syncs new product content to Server. <br/>
 * It provides a User Interface to Admin User.
 * 
 */
public class AddProducts extends Fragment {

	public AddProducts() {
	}

	TextView user, error;
	String data;
	Button submit;
	EditText product;
	String newproduct;
	String responseString;
	AsyncTask<Void, Void, Void> mRegisterTask;
	String dataaddition = null, notsuccessful = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.addproducts, container, false);
		user = (TextView) v.findViewById(R.id.tvUser);
		product = (EditText) v.findViewById(R.id.etAddproduct);
		error = (TextView) v.findViewById(R.id.textViewError);
		data = this.getActivity().getIntent().getExtras().getString("username");
		user.setText(data);
		submit = (Button) v.findViewById(R.id.btnSubmit);
		submit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				newproduct = product.getText().toString();
				if (!newproduct.isEmpty()) {

					getActivity().setProgressBarIndeterminateVisibility(true);

					mRegisterTask = new AsyncTask<Void, Void, Void>() {

						@Override
						protected Void doInBackground(Void... params) {
							try {

								HttpClient http = new DefaultHttpClient();
								String server = AppVars.getServer();
								HttpPost post = new HttpPost(
										"http://"
												+ server
												+ "/gcminteraction/view/start.php?controlVar=17");
								List<NameValuePair> data = new ArrayList<NameValuePair>();
								data.add(new BasicNameValuePair("usertype",
										AppVars.sloggedInUserType));
								Log.w("UserId", AppVars.sloggedInUserType);
								data.add(new BasicNameValuePair("producttype",
										newproduct));
								post.setEntity(new UrlEncodedFormEntity(data));

								HttpResponse response = http.execute(post);
								responseString = new BasicResponseHandler()
										.handleResponse(response);

								Log.w("Response String =", responseString);

								JSONObject obj;
								try {
									obj = new JSONObject(responseString);

									if (obj.isNull("not successful")) {
										dataaddition = obj
												.getString("data addition");
										notsuccessful = "";

									} else if (obj.isNull("data addition")) {
										notsuccessful = obj
												.getString("not successful");
										dataaddition = "";
									}

								} catch (JSONException e) {
									e.printStackTrace();
								}

							} catch (ClientProtocolException e) {

							} catch (IOException e) {

							}
							return null;

						}

						@Override
						protected void onPostExecute(Void result) {
							getActivity()
									.setProgressBarIndeterminateVisibility(
											false);

							if (notsuccessful.equals("-1")) {
								product.setText("");
								Toast.makeText(getActivity(),
										"Product Not Submitted",
										Toast.LENGTH_LONG).show();
							} else if (dataaddition.equals("1")) {
								product.setText("");

								DbHelper db = new DbHelper(getActivity());
								db.open();
								db.insert_product_data(newproduct);
								db.close();

								Toast.makeText(getActivity(),
										"Product Submitted", Toast.LENGTH_LONG)
										.show();
							}

						}
					};
					mRegisterTask.execute(null, null, null);

				} else {
					error.setText("Field cannot be left blank");
				}

			}
		});

		return v;
	}

}
